<?php

namespace controller;

/**
 * kontroler obsłujący jQuery
 *
 * @author Damian
 */
class Ajax extends Controller {

    public function __construct($options = array()) {

        $this->willRenderActionView = false;
        $this->willRenderLayoutView = false;
        parent::__construct($options);
    }

    public function getAdress() {
        $code = \library\RequestMethods::post("code");
        $adressCriteria = new \model\Criteria();
        $adressCriteria->from(\model\TblPostCode::getModel()->getTable())
                ->join(\model\TblRegion::getModel())
                ->join(\model\TblDistrict::getModel())
                ->join(\model\TblCommunity::getModel())
                ->join(\model\TblCity::getModel())
                ->join(\model\TblStreet::getModel())
                ->where(\model\TblPostCode::CODE, "=", $code);
        $postCodes = \model\TblPostCode::getModel()->all($adressCriteria);
        if (!$postCodes) {
            echo json_encode(null);
            return;
        }
        //$a
        $model = new \model\DataTable($postCodes, false);
        $modelData = $model->getModelData();
        //var_dump($modelData);
        $result = array();
        $result["RegionID"] = $modelData[0]["RegionID"]["Name"];
        $result["DistrictID"] = $modelData[0]["DistrictID"]["Name"];
        $result["CommunityID"] = $modelData[0]["CommunityID"]["Name"];
        if ($modelData[0]["StreetID"]["Name"] == "brak") {
            $result["StreetID"] = false;
            foreach ($modelData as $model) {
                $result["CityID"][] = ["Name" => $model["CityID"]["Name"], "ID" => $model["CityID"]["CityID"]];
            }
        } else {
            $result["CityID"] = $modelData[0]["CityID"]["Name"];
            foreach ($modelData as $model) {
                $result["StreetID"][] = ["Name" => $model["StreetID"]["Name"], "ID" => $model["StreetID"]["StreetID"]];
            }
        }
        // var_dump($result);
        echo json_encode($result);
    }

    public function progress() {
        if (!isset($_SESSION)) {
            session_start();
        }
        echo json_encode($_SESSION['upload_progress_my_files']);
    }

    public function upload() {
        $date = new \DateTime();
        if (isset($_FILES["Filedata"])) {
            if (isset($_GET["time"])) {
                $name = $_GET["time"] . ".txt";
                $plik = new \SplFileObject($name, "w");
                try {
                    $file = new \library\Picture("Filedata", $_GET["shopname"]);

                    $tblPicture = new \model\TblPicture(
                            [
                        \model\TblPicture::NAME => $file->Name,
                        \model\TblPicture::SHOP_ID => $_GET["sellerid"],
                        \model\TblPicture::DELETED => 0,
                        \model\TblPicture::MIME => $file->Mime,
                        \model\TblPicture::CREATED => $date->format('Y-m-d H:i:s'),
                        \model\TblPicture::MODIFIED => $date->format('Y-m-d H:i:s')
                    ]);
                    $tblPicture->save();
                    $plik->fwrite("ok");
                    $file->createThumb(128, 128);
                    $file->createThumb(300, 300);
                    $file->createThumb(800, 800);
                } catch (RuntimeException $exc) {
                    $plik->fwrite($exc->getMessage());
                } catch (\model\exceptions\ExceptionSQLQUery $ex) {
                    if ($ex->getCode() == 1062) {
                        $plik->fwrite("Obrazek o takiej nazwie już istnieje");
                    } else {
                        $plik->fwrite($ex->getMessage());
                    }
                } catch (\Exception $e) {
                    $plik->fwrite($e->getMessage());
                }
            }
        }
    }

    public function usun() {
        if (\library\RequestMethods::get("time") != null) {//kasowanie pliku tymczasowego do uploadu
            unlink(\library\RequestMethods::get("time") . ".txt");
        }
    }

    public function getCategoryFeatures() {
        $CategoryID = \library\RequestMethods::post("category");
        if ($CategoryID) {
            $categoryCriteria = new \model\Criteria();
            $categoryCriteria->from(\model\TblCategory::getModel()->getTable())->where(\model\TblCategory::ID, "=", $CategoryID);
            $category = \model\TblCategory::getModel()->first($categoryCriteria);
            $IDs = $category->getAllIds();
            $featuresCriteria = new \model\Criteria();
            $featuresCriteria->from(\model\TblCategoryFeature::getModel()->getTable())
                    ->in(\model\TblCategoryFeature::CATEGORY_ID, $IDs);
            $features = \model\TblCategoryFeature::getModel()->all($featuresCriteria);
            if (sizeof($features) == 0) {
                echo json_encode(false);
                return;
            }
            $model = new \model\DataTable($features, false);
            $modelData = $model->getModelData();
            foreach ($modelData as &$cat) {
                $valueCriteria = new \model\Criteria();
                $valueCriteria->from(\model\TblFeatureValue::getModel()->getTable());
                $valueCriteria->where(\model\TblFeatureValue::CATEGORY_FEATURE_ID, "=", $cat["CategoryFeatureID"]);
                $values = new \model\DataTable(\model\TblFeatureValue::getModel()->all($valueCriteria));
                $cat["values"] = $values->getModelData();
            }
            //     var_dump($modelData);
            echo json_encode($modelData);
        }
    }

    public function autocomplete() {
        $CategoryID = \library\RequestMethods::post("category");
        if ($CategoryID) {
            $categoryCriteria = new \model\Criteria();
            $categoryCriteria->from(\model\TblProduct::getModel()->getTable())
                    ->where(\model\TblProduct::NAME, " like ", "%" . $CategoryID . "%")
                    ->where(\model\TblProduct::VISABLE, "=", 1, false, " and ")
                    ->where(\model\TblProduct::ACTIVE, "=", 1, false, " and ")
                    ->where(\model\TblProduct::SHOP_ID, "=", $this->shop->ShopID, false, " and ")
                    ->limit(10);
            $category = \model\TblCategoryFeature::getModel()->all($categoryCriteria);
            if (sizeof($category) == 0) {
                echo json_encode(false);
                return;
            }
            $model = new \model\DataTable($category, false);
            $modelData = $model->getModelData();
            //     var_dump($modelData);
            echo json_encode($modelData);
        }
    }

    public function searchCustomer() {
        $name = \library\RequestMethods::post("name");
        if ($name) {
            $Criteria = new \model\Criteria();
            $Criteria->from(\model\TblCustomer::getModel()->getTable())
                    ->join(\model\TblPerson::getModel());
            $array = explode(" ", $name, 2);
            if (sizeof($array) == 2) {
                $Criteria->where(\model\TblPerson::NAME, " like ", "%" . $array[0] . "%")
                        ->where(\model\TblPerson::SURNAME, " like ", "%" . $array[1] . "%", false, " and ");
            } else if (sizeof($array) == 1) {
                $Criteria->where(\model\TblPerson::PHONE_NUMBER, " like ", "%" . $name . "%")
                        ->where(\model\TblPerson::NAME, " like ", "%" . $name . "%", false, " or ")
                        ->where(\model\TblPerson::SURNAME, " like ", "%" . $name . "%", false, " or ")
                        ->where(\model\TblPerson::EMAIL, " like ", "%" . $name . "%", false, " or ");
            } else {
                echo json_encode(false);
                return;
            }
            $customers = \model\TblCustomer::getModel()->all($Criteria->limit(10));
            if (sizeof($customers) == 0) {
                echo json_encode(false);
                return;
            }
            $model = new \model\DataTable($customers, false);
            $modelData = $model->getModelData();
            echo json_encode($modelData);
        } else {
            echo json_encode(false);
            return;
        }
    }

    public function getMessage() {
        $criteria = new \model\Criteria();
        $answer = $criteria->from(\model\TblAnswer::getModel()->getTable())
                        ->where(\model\TblAnswer::ID, ">", \library\RequestMethods::post("maxID"))
                        ->limit(1)->all();
        if (sizeof($answer) > 0) {
            echo json_encode($answer[0]["tblanswer"]);
        } else {
            echo json_encode(false);
        }
    }

    public function sendMessage() {
        $convID = \library\RequestMethods::post("convID");
        $message = \library\RequestMethods::post("message");
        $session = \library\Registry::get("session");
        $customer = $session->get("customer");
        $seller = $session->get("seller");
        $sendByCustomer = "";
        if ($customer) {
            $sendByCustomer = 1;
        } else if ($seller) {
            $sendByCustomer = 0;
        } else {
            return false;
        }
        $date = new \DateTime();
        $answer = new \model\TblAnswer([
            \model\TblAnswer::CONTENT => $message,
            \model\TblAnswer::SEND_BY_CUSTOMER => $sendByCustomer,
            \model\TblAnswer::CONVERSATION_ID => $convID,
            \model\TblAnswer::ADDITION_DATE => $date->format('Y-m-d H:i:s'),
            \model\TblAnswer::SEEN => 0
        ]);
        echo json_encode($answer);
        $answer->save();
    }

    public function beginConv() {
        $topic = \library\RequestMethods::post("topic");
        $message = \library\RequestMethods::post("message");
        $session = \library\Registry::get("session");
        $customer = $session->get("customer");
        $seller = $session->get("seller");
        $sendByCustomer = "";
        if ($customer) {
            $sendByCustomer = 1;
        } else if ($seller) {
            $sendByCustomer = 0;
        } else {
            return false;
        }
        $date = new \DateTime();
        $conversation = new \model\TblConversation([
            \model\TblConversation::CUSTOMER_ID => $customer->CustomerID,
            \model\TblConversation::ADDITION_DATE => $date->format('Y-m-d H:i:s'),
            \model\TblConversation::SHOP_ID => $customer->ShopID,
            \model\TblConversation::TOPIC => $topic
        ]);
        $convID = $conversation->save();
        $answer = new \model\TblAnswer([
            \model\TblAnswer::CONTENT => $message,
            \model\TblAnswer::SEND_BY_CUSTOMER => $sendByCustomer,
            \model\TblAnswer::CONVERSATION_ID => $convID,
            \model\TblAnswer::ADDITION_DATE => $date->format('Y-m-d H:i:s'),
            \model\TblAnswer::SEEN => 0
        ]);
        $answer->save();
    }

    public function beginConvAsSeller() {
        $topic = \library\RequestMethods::post("topic");
        $message = \library\RequestMethods::post("message");
        $session = \library\Registry::get("session");
        $customerID = \library\RequestMethods::post("customer");
        $shopID = \library\RequestMethods::post("shop");
        $seller = $session->get("seller");
        $sendByCustomer = "";
        $customer = \model\TblCustomer::getModel()->getByPrimaryKey($customerID);
        $shop = \model\TblShop::getModel()->getByPrimaryKey($shopID);
        if ($seller) {
            $sendByCustomer = 0;
        } else {
            return false;
        }
        if ($shop->ShopID != $customer->ShopID) {
            return false;
        }
        $date = new \DateTime();
        $conversation = new \model\TblConversation([
            \model\TblConversation::CUSTOMER_ID => $customer->CustomerID,
            \model\TblConversation::ADDITION_DATE => $date->format('Y-m-d H:i:s'),
            \model\TblConversation::SHOP_ID => $customer->ShopID,
            \model\TblConversation::TOPIC => $topic
        ]);
        $convID = $conversation->save();
        $answer = new \model\TblAnswer([
            \model\TblAnswer::CONTENT => $message,
            \model\TblAnswer::SEND_BY_CUSTOMER => $sendByCustomer,
            \model\TblAnswer::CONVERSATION_ID => $convID,
            \model\TblAnswer::ADDITION_DATE => $date->format('Y-m-d H:i:s'),
            \model\TblAnswer::SEEN => 0
        ]);
        $answer->save();
    }

    public function markAsRead() {
        $convID = \library\RequestMethods::post("convID");
        $messageID = \library\RequestMethods::post("messageID");
        $answerCriteria = new \model\Criteria();
        $answerCriteria->from(\model\TblAnswer::getModel()->getTable())
                ->where(\model\TblAnswer::ID, "=", $messageID)
                ->where(\model\TblAnswer::CONVERSATION_ID, "=", $convID, false, " and ");
        $message = \model\TblAnswer::getModel()->first($answerCriteria);
        if ($message) {
            $message->Seen = 1;
            $message->save();
        }
    }

    public function updateDiscount() {
        $customerID = \library\RequestMethods::post("customer");
        if ($customerID) {
            $customer = \model\TblCustomer::getModel()->getByPrimaryKey($customerID);
            $customer->Discount = \library\RequestMethods::post("discountVal");
            $customer->save();
        }
    }

    public function addFeatureValue() {
        $featureID = \library\RequestMethods::post("featureID");
        $value = \library\RequestMethods::post("value");
        if ($value && $featureID) {
            $valueFeature = new \model\TblFeatureValue([
                \model\TblFeatureValue::VALUE => $value,
                \model\TblFeatureValue::CATEGORY_FEATURE_ID => $featureID
            ]);
            $valueFeature->save();
        }
    }

    public function getFeatureValue() {
        $featureID = \library\RequestMethods::post("featureID");
        if ($featureID) {
            $valueCriteria = new \model\Criteria();
            $valueCriteria->from(\model\TblFeatureValue::getModel()->getTable());
            $valueCriteria->where(\model\TblFeatureValue::CATEGORY_FEATURE_ID, "=", $featureID);
            $values = new \model\DataTable(\model\TblFeatureValue::getModel()->all($valueCriteria));
            echo json_encode($values->getModelData(false));
        }
    }

}
